//
//  TKYAddQualityMessageController.m
//  填报进度质量
//
//  Created by apple on 2018/7/25.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYAddQualityMessageController.h"
#import "TKYTitleTextField.h"
#import "TKYDesView.h"
#import "TKYAddImageOrVideoView.h"
#import <Photos/Photos.h>
#import "GQImageVideoViewer.h"
#import "TKYDataConnectionView.h"
#import "TKYFindTreeController.h"
#import "BRPickerView.h"
#import "TKYSelectedFileController.h"
#import "TKYSelectedPersonController.h"
#import "TKYQuestionTypeController.h"
#import "TKYQuestionLevelController.h"
#import "CalculateTextHeight.h"
#import "TKYTitleTextView.h"
@interface TKYAddQualityMessageController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UIView *view;
    UIView *_supDataView;
}

@property (nonatomic, strong)UIScrollView *scrollV;

/** 任务标题*/
@property (nonatomic, strong) TKYTitleTextField *titleView;
/**类型*/
@property (nonatomic, strong) TKYTitleTextView *typeView;
/**问题级别*/
@property (nonatomic, strong) TKYTitleTextField *questionLevelView;
/**考核分数*/
@property (nonatomic, strong) TKYTitleTextField *scoreView;
/**问题描述*/
@property (nonatomic, strong) TKYDesView *questionDesView;
/**措施要求*/
@property (nonatomic, strong) TKYDesView *measuresRequiredView;
/**照片或视频*/
@property (nonatomic, strong) TKYAddImageOrVideoView *imageVideoView;
/**截至日期*/
@property (nonatomic, strong) TKYTitleTextField *dateView;
/**资料模型label*/
@property (nonatomic, strong) UILabel *dataLabel;

/**资料关联*/
@property (nonatomic, strong) TKYDataConnectionView *dadaView;
/**模型关联*/
//@property (nonatomic, strong) TKYTitleTextField *questionLevelView;
/**分部分项*/
@property (nonatomic, strong) TKYTitleTextField *subdivisionView;
/**相关人员label*/
@property (nonatomic, strong) UILabel *personLabel;
@property (nonatomic, strong)UIView *personView;
/**责任人*/
@property (nonatomic, strong) TKYTitleTextField *liablePersonlView;
/**督办人*/
@property (nonatomic, strong) TKYTitleTextField *supervisorView;
/**验收人*/
@property (nonatomic, strong) TKYTitleTextField *acceptorView;
/**抄送人*/
@property (nonatomic, strong) TKYTitleTextField *ccPersonView;

@property (nonatomic, assign)BOOL isCamera;

/**标题*/
@property (nonatomic, strong)NSString *questionName;
/**问题类型*/
@property (nonatomic, strong)NSString *questionType;
/**问题等级*/
@property (nonatomic, strong)NSString *questionLevel;
/**考核分数*/
@property (nonatomic, strong)NSString *scoreStr;
/**问题描述*/
@property (nonatomic, strong)NSString *questionDescription;
/**措施要求*/
@property (nonatomic, strong)NSString *measuresRequired;
/**图片或视频*/
@property (nonatomic, strong)NSMutableArray *imageArrM;
/**限改日期 */
@property (nonatomic, strong)NSString *modificationDateStr;
/**资料关联*/
@property (nonatomic, strong)NSString *documentId;
/**分部分项*/
@property (nonatomic, strong)NSString *subdivisionId;
/**发起人*/
@property (nonatomic, strong)NSString *initiator;
/**责任人*/
@property (nonatomic, strong)NSString *supervisor;
/**督办人*/
@property (nonatomic, strong)NSString *acceptor;
/**验收人*/
@property (nonatomic, strong)NSString *ccPerson;
/**状态*/
@property (nonatomic, strong)NSString *processStatus;

@end

@implementation TKYAddQualityMessageController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航
    [self setupNavigation];
    
    [self initUI];
    
}

/**发送按钮*/
- (void)sendAction:(UIBarButtonItem *)barButtonItem{
    NSLog(@"%@", self.imageArrM);
    NSMutableArray *imageM = [NSMutableArray array];
    
    if (self.questionName.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请输入任务标题"];
        return;
    }
    
    if (self.questionType.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请选择问题类型"];
        return;
    }
    
    if (self.questionLevel.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请选择问题级别"];
        return;
    }
    
    if (self.scoreStr.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请填写考核分数"];
        return;
    }
    
    if (self.questionDescription.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"问题描述不能为空"];
        return;
    }
    
    if (self.questionDescription.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"措施要求不能为空"];
        return;
    }
    
    if (self.modificationDateStr.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请选择截至时间"];
        return;
    }
    NSLog(@"%@",imageM);
    NSDictionary *parameters = @{
                                 @"token":[[NSUserDefaults standardUserDefaults]objectForKey:kToken],
                                 @"safeQualityFlag":@"1",
                                 @"delFlag":@"0",
                                 @"projectId":@"",
                                 @"questionName":self.questionName,
                                 @"questionType":self.questionType,
                                 @"questionLevel":self.questionLevel,
                                 @"score":self.scoreStr,
                                 @"questionDescription":self.questionDescription,
                                 //@"fileList":imageM,
                                 @"modificationDateStr":self.modificationDateStr,
                                 @"documentId":@"",
                                 @"subdivisionId":@"",
                                 @"initiator":@"",
                                 @"liablePerson":@"",
                                 @"supervisor":@"",
                                 @"acceptor":@"",
                                 @"ccPerson":@"",
                                 @"processStatus":@"",
                                 };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [SVProgressHUD showSVProgressHUDWithAnimationType:SVProgressHUDAnimationTypeFlat maskType:SVProgressHUDMaskTypeBlack style:SVProgressHUDStyleDark status:@"正在提交数据"];
    
    [manager POST:[NSString stringWithFormat:@"%@%@",kApiBaseUrl,KSaveQuestionUrl] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传视频和图片
        for (NSDictionary *dic in self.imageArrM) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            NSString *str=[formatter stringFromDate:[NSDate date]];
            if ([[dic objectForKey:@"GQIsImageURL"]integerValue] == 1) {
                NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
                UIImage *image = dic[GQURLString];
                // UIImage *compreImage = [image scaleToWidth:1024];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                [formData appendPartWithFileData:imageData name:@"uploadFileList" fileName:fileName mimeType:@"image/png"];
            }else{
                NSData *fileData = [NSData dataWithContentsOfFile:dic[GQURLString]];
                [formData appendPartWithFileData:fileData name:@"uploadFileList" fileName:[NSString stringWithFormat:@"%@.mp4",str] mimeType:@"application/octet-stream"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"]integerValue] == 0) {
            [SVProgressHUD dismiss];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:responseObject[@"msg"]];;
        }
        NSLog(@"===%@, %@", responseObject[@"msg"],responseObject[@"code"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"网络错误, 请稍候再试"];
    }];
#warning 发送按钮
    NSLog(@"分数%@", self.scoreStr);
}


- (void)initUI{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollV];
   
    __weak typeof(self) weakSelf = self;
    __weak typeof(view) weakView = view;

    //任务标题
    self.titleView = [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeightScale *44) titleLabelText:@"任务标题" placeholderText:@"请输入标题"];
    self.titleView.selectedButton.hidden = YES;
    self.titleView.imageV.hidden = YES;
    self.titleView.textFieldFBlock = ^(NSString *str) {
        NSLog(@"%@", str);
        weakSelf.questionName = str;
    };
    [self.scrollV addSubview:self.titleView];
    //类型
    self.typeView = [[TKYTitleTextView alloc]initWithFrame:CGRectMake(0, self.titleView.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"类型" placeholderText:@"请选择"];
    self.typeView.selectedButtonBlock = ^(UIButton *button) {
        TKYQuestionTypeController *questionTypeVC = [TKYQuestionTypeController new];
        questionTypeVC.selectedQuestionTypeBlock = ^(TKYQuestionTypeModel *questionType) {
//            questionType.name = @"asdasefdghjkl;ytrewrtyuiopiuytrewrtyuiouytrewqertyuiyhgcm vcfniohipdrjiephgijgifdjkn xnfohewenlnkf";
            [weakSelf.typeView.selectedButton setTitle:@"" forState:UIControlStateNormal];
            CGFloat height = [CalculateTextHeight heightForString:questionType.name fontSize:14 andWidth:200];
            if (height > 44) {
                weakSelf.typeView.frame = CGRectMake(0, weakSelf.titleView.kx_bottom, kScreenWidth,height);
            }else{
                weakSelf.typeView.frame = CGRectMake(0, weakSelf.titleView.kx_bottom, kScreenWidth,44);
            }
           // weakView.frame = CGRectMake(0, weakSelf.typeView.kx_bottom, kScreenWidth, kHeightScale *44 *3 +kHeightScale *350);
             weakSelf.typeView.contentLabel.text = questionType.name;
            weakSelf.questionType = questionType.name;
                };
        [weakSelf.navigationController pushViewController:questionTypeVC animated:YES];
    };
    [self.scrollV addSubview:self.typeView];
   
    //类型往下的view 放到了这个view上, 为了点击类型选择改变view的位置
    view = [[UIView alloc]initWithFrame:CGRectMake(0, self.typeView.kx_bottom, kScreenWidth, kHeightScale *44 *3 +kHeightScale *350)];
    [self.scrollV addSubview:view];
    //问题级别
    self.questionLevelView = [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeightScale *44) titleLabelText:@"问题级别" placeholderText:@"请选择"];
    self.questionLevelView.selectedButtonBlock = ^(UIButton *button) {
        TKYQuestionLevelController *questionLevelVC = [TKYQuestionLevelController new];
        questionLevelVC.selectedQuestionLevelBlock = ^(TKYQuestionLevelModel *questionLevel) {
            
            weakSelf.questionLevelView.textField.text = questionLevel.name;
            weakSelf.questionLevel = questionLevel.name;
        };
        [weakSelf.navigationController pushViewController:questionLevelVC animated:YES];
    };
    [view addSubview:self.questionLevelView];
    
    //考核分数
    self.scoreView = [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.questionLevelView.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"考核分数" placeholderText:@"请选择"];
    self.scoreView.selectedButton.hidden = YES;
    self.scoreView.imageV.hidden = YES;
     self.scoreView.textField.keyboardType = UIKeyboardTypeNumberPad;
    self.scoreView.textFieldFBlock = ^(NSString *str) {
        NSLog(@"%@", str);
        weakSelf.scoreStr = str;
    };
    [view addSubview:self.scoreView];
    
    
    //问题描述
    self.questionDesView = [[TKYDesView alloc]initWithFrame:CGRectMake(0, self.scoreView.kx_bottom, kScreenWidth, kHeightScale *100) titleLabelText:@"问题描述"];
    self.questionDesView.placeholderStr = @"问题描述";
    self.questionDesView.describeTextBlock = ^(NSString *describeText) {
        NSLog(@"问题描述:%@", describeText);
        weakSelf.questionDescription = describeText;
    };
    [view addSubview:self.questionDesView];
    
    //措施要求
    self.measuresRequiredView = [[TKYDesView alloc]initWithFrame:CGRectMake(0, self.questionDesView.kx_bottom, kScreenWidth, kHeightScale *100) titleLabelText:@"措施要求" ];
    self.measuresRequiredView.placeholderStr = @"措施要求";
    self.measuresRequiredView.describeTextBlock = ^(NSString *describeText) {
        NSLog(@"措施要求:%@",describeText);
         weakSelf.measuresRequired = describeText;
    };
    [view addSubview:self.measuresRequiredView];
    
    //照片或视频
    self.imageVideoView = [[TKYAddImageOrVideoView alloc]initWithFrame:CGRectMake(0, self.measuresRequiredView.kx_bottom, kScreenWidth, kHeightScale *150) ];
    self.imageVideoView.addCameraBlock = ^(UIButton *button) {
        [weakSelf addImage:button];
    };
    self.imageVideoView.seletetedCollectionCellBlock = ^(NSIndexPath *indexPath) {
        NSInteger indexChain = indexPath.row;
        [GQImageVideoViewer sharedInstance]
        .videoViewClassNameChain(@"TKYVideoView")
        .dataArrayChain(weakSelf.imageArrM)
        .showIndexTypeChain(GQShowIndexTypeLabel)
        .selectIndexChain(indexChain)
        .achieveSelectIndexChain(^(NSInteger selectIndex){
            NSLog(@"%zd",selectIndex);
        })
        .launchDirectionChain(GQLaunchDirectionRight)
        .showViewChain(weakSelf.navigationController.view);
    };
    [view addSubview:self.imageVideoView];
    
    //截至日期
    self.dateView = [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.imageVideoView.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"截至日期" placeholderText:@"请选择"];
    self.dateView.selectedButtonBlock = ^(UIButton *button) {
        [BRDatePickerView showDatePickerWithTitle:@"请选择截至日期" dateType:BRDatePickerModeYMD defaultSelValue:@"" resultBlock:^(NSString *selectValue) {
            weakSelf.dateView.textField.text = selectValue;
            weakSelf.modificationDateStr = selectValue;
        }];
    };
    [view addSubview:self.dateView];
    //资料模型的view
    [self initDataModelView];
    [self initPersonView];
}

//资料模型
- (void)initDataModelView{
    self.dataLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, view.kx_bottom, kScreenWidth, kHeightScale*30)];
    self.dataLabel.backgroundColor = kMainColour;
    self.dataLabel.text = @"  资料关联";
    self.dataLabel.font = Font(12);
    [self.scrollV addSubview:self.dataLabel];
    
    //资料关联
    self.dadaView = [[TKYDataConnectionView alloc]initWithFrame:CGRectMake(0, self.dataLabel.kx_bottom, kScreenWidth, kHeightScale *44)];
    self.dadaView.deleteButton.hidden = YES;
    __weak typeof(self) weakSelf = self;
    //点击了选择资料按钮
    self.dadaView.seletetedButtonBlock = ^(UIButton *button) {
         TKYSelectedFileController *selectedFileVC = [[TKYSelectedFileController alloc]init];
         selectedFileVC.returnValueBlock = ^(NSString *strValue) {
             weakSelf.dadaView.contentLabel.text = strValue;
             [weakSelf.dadaView.selectedBtn setTitle:@"已关联" forState:UIControlStateNormal];
             weakSelf.dadaView.frame = CGRectMake(0, weakSelf.dataLabel.kx_bottom, kScreenWidth, kHeightScale *60);
             weakSelf.subdivisionView.frame = CGRectMake(0, weakSelf.dadaView.kx_bottom, kScreenWidth, kHeightScale *44);
             weakSelf.personView.frame = CGRectMake(0, weakSelf.subdivisionView.kx_bottom, kScreenWidth, kHeightScale*150);
             weakSelf.dadaView.deleteButton.hidden = NO;
             //点击了删除按钮
             weakSelf.dadaView.deleteButtonBlock = ^(UIButton *button) {
                 weakSelf.dadaView.deleteButton.hidden = YES;
                 [weakSelf.dadaView.selectedBtn setTitle:@"请关联" forState:UIControlStateNormal];
                 weakSelf.dadaView.contentLabel.text = @"";
                 weakSelf.dadaView.frame = CGRectMake(0, weakSelf.dataLabel.kx_bottom, kScreenWidth, kHeightScale *44);
                 weakSelf.subdivisionView.frame = CGRectMake(0, weakSelf.dadaView.kx_bottom, kScreenWidth, kHeightScale *44);
                 weakSelf.personView.frame = CGRectMake(0, weakSelf.subdivisionView.kx_bottom, kScreenWidth, kHeightScale*150);
             };
         };
        [weakSelf.navigationController pushViewController:selectedFileVC animated:YES];
    };
    [self.scrollV addSubview:self.dadaView];
    
//    //模型关联
//    self.questionDesView = [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.questionLevelView.kx_bottom, kScreenWidth, kHeightScale *40) titleLabelText:@"问题描述" placeholderText:@"请选择"];
//    self.questionLevelView.selectedButtonBlock = ^(UIButton *button) {
//        NSLog(@"123");
//    };
//    [self.scrollV addSubview:self.questionDesView];
    
    //分部分项
    self.subdivisionView = [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.dadaView.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"分部分项" placeholderText:@"请选择"];
    self.subdivisionView.selectedButtonBlock = ^(UIButton *button) {
        NSLog(@"分部分项");
        TKYFindTreeController *findTreeVC = [TKYFindTreeController new];
        findTreeVC.selectedBlock = ^(TKYFindTreeModel *findTreeModel) {
            weakSelf.subdivisionView.textField.text = findTreeModel.name;
        };
        [weakSelf.navigationController pushViewController:findTreeVC animated:YES];
    };
    [self.scrollV addSubview:self.subdivisionView];
}


/**相关人员 */
- (void)initPersonView{
    __weak typeof(self) weakSelf = self;
    self.personView = [[UIView alloc]initWithFrame:CGRectMake(0,self.subdivisionView.kx_bottom, kScreenWidth, kHeightScale*300)];
    [self.scrollV addSubview:self.personView];
    
    self.personLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeightScale*30)];
    self.personLabel.text = @"   相关人员";
    self.personLabel.font = Font(12);
    self.personLabel.backgroundColor = kMainColour;
    [self.personView addSubview:self.personLabel];
    //责任人
    self.liablePersonlView= [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.personLabel.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"责任人" placeholderText:@"请选择"];
    self.liablePersonlView.selectedButtonBlock = ^(UIButton *button) {
        TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
        selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
            
            weakSelf.liablePersonlView.textField.text = [weakSelf getPerson:memberS];;
        };
        [weakSelf.navigationController pushViewController:selectedVC animated:YES];
    };
    [self.personView addSubview:self.liablePersonlView];
    
    //督办人
    self.supervisorView= [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.liablePersonlView.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"督办人" placeholderText:@"请选择"];
    self.supervisorView.selectedButtonBlock = ^(UIButton *button) {
        TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
        selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
            
            weakSelf.supervisorView.textField.text = [weakSelf getPerson:memberS];;
        };
        
        [weakSelf.navigationController pushViewController:selectedVC animated:YES];
    };
    [self.personView addSubview:self.supervisorView];
    
    //验收人
    self.acceptorView= [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.supervisorView.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"验收人" placeholderText:@"请选择"];
    self.acceptorView.selectedButtonBlock = ^(UIButton *button) {
        TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
        selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
            
            weakSelf.acceptorView.textField.text = [weakSelf getPerson:memberS];;
        };
        [weakSelf.navigationController pushViewController:selectedVC animated:YES];
    };
    [self.personView addSubview:self.acceptorView];
    
    //抄送人
    self.ccPersonView= [[TKYTitleTextField alloc]initWithFrame:CGRectMake(0, self.acceptorView.kx_bottom, kScreenWidth, kHeightScale *44) titleLabelText:@"抄送人" placeholderText:@"请选择"];
    //self.ccPersonView.selectedButton.backgroundColor = [UIColor redColor];
    self.ccPersonView.selectedButtonBlock = ^(UIButton *button) {
        TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
        selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
            
            weakSelf.ccPersonView.textField.text = [weakSelf getPerson:memberS];;
        };
        [weakSelf.navigationController pushViewController:selectedVC animated:YES];
    };
    [self.personView addSubview:self.ccPersonView];

}

/**
 设置导航
 */
- (void)setupNavigation{
    self.navigationItem.title = @"安全填报";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_btn"]  style:UIBarButtonItemStylePlain target:self action:@selector(backButton:)];
    //设置导航栏文字颜色
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendAction:)];
}

- (void)setUPUI{
    [self.view addSubview:self.scrollV];
}

#pragma mark--添加图片
- (void)addImage:(UIButton *)button{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"选择照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoLibraryImage];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isCamera = YES;
        [self phonCameraImage];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"选择视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self choosevideo];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"录制视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isCamera = YES;
        [self startvideo];
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    
}

//拍摄照片
- (void)phonCameraImage{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.delegate = self;//设置委托
    
}

//选择相册图片
- (void)photoLibraryImage{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.delegate = self;//设置委托
}

//选择本地视频
- (void)choosevideo
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.delegate = self;//设置委托
    
}

//录制视频
- (void)startvideo
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    ipc.delegate = self;//设置委托
    ipc.videoMaximumDuration = 10.0f;//30秒
    ipc.accessibilityLanguage = NSCalendarIdentifierChinese ;
    [self presentViewController:ipc animated:YES completion:nil];
}

- (CGFloat) getFileSize:(NSString *)path
{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}

//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getVideoLength:(NSURL *)URL
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}//此方法可以获取视频文件的时长。

//完成视频录制，并压缩后显示大小、时长
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image;
    NSString *key;
    NSDictionary *dict;
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    key = [NSString stringWithFormat:@"%p%@",image,@"NO"];
    if (image) {
        dict = @{
                 GQIsImageURL:@(YES),
                 GQURLString:image,
                 @"image":image
                 };
    }
    
    //UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
    NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
    NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);
    NSURL *newVideoUrl ; //一般.mp4
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
    //获取第一帧的图片
    if (sourceURL) {
        image = [self firstFrameWithVideoURL:sourceURL size:CGSizeMake(100, 100)];
        key = [NSString stringWithFormat:@"%p%@",image,@"YES"];
        dict = @{
                 GQIsImageURL:@(NO),
                 GQURLString:sourceURL,
                 @"image":image
                 };
    }
    [self.imageArrM addObject:dict];
    self.imageVideoView.imageArr = self.imageArrM;
    [self.imageVideoView.collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}

//压缩视频
- (void)convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                              outputURL:(NSURL*)outputURL
                        completeHandler:(void (^)(AVAssetExportSession*))handler
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    //  NSLog(resultPath);
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:
                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
                 NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
                 
                 //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
                 [self alertUploadVideo:outputURL];
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
         }
     }];
}

//是否上传视频
-(void)alertUploadVideo:(NSURL*)URL{
    CGFloat size = [self getFileSize:[URL path]];
    NSString *message;
    NSString *sizeString;
    CGFloat sizemb= size/1024;
    if(size<=1024){
        sizeString = [NSString stringWithFormat:@"%.2fKB",size];
    }else{
        sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
    }
    
    
    if(sizemb<2){
        [self uploadVideo:URL];
    }
    
    else if(sizemb<=5){
        message = [NSString stringWithFormat:@"视频%@，大于2MB会有点慢，确定上传吗？", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                  message: message
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间（沙盒）
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self uploadVideo:URL];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }else if(sizemb>5){
        message = [NSString stringWithFormat:@"视频%@，超过5MB，不能上传，抱歉。", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil message: message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}



/**
 上传视频
 */
-(void)uploadVideo:(NSURL*)URL{
    
    
}


#pragma mark ---- 获取图片第一帧
- (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
{
    // 获取视频第一帧
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(size.width, size.height);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
    {
        return [UIImage imageWithCGImage:img];
    }
    return nil;
}

#pragma mark-- 懒加载
- (NSMutableArray *)imageArrM{
    if (!_imageArrM) {
        _imageArrM = [NSMutableArray array];
    }
    return _imageArrM;
}

/**
 返回按钮*/
- (void)backButton:(UIBarButtonItem *)barButtonItem{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (UIScrollView *)scrollV {
    if (_scrollV == nil) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        _scrollV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight )];
        _scrollV.scrollEnabled = YES;
        //_scrollV.pagingEnabled = YES;
        _scrollV.showsHorizontalScrollIndicator = NO;
        _scrollV.showsVerticalScrollIndicator = YES;
        _scrollV.contentSize = CGSizeMake(0, kScreenHeight *1 +kHeightScale *300);
    }
    return _scrollV;
}

- (NSString *)getPerson:(NSArray *)arr{
    NSMutableString *strM = [NSMutableString string];
    
    if (arr.count == 1) {
        return  strM = arr.lastObject;
    }
    for (NSString *personStr in arr) {
        
        [strM appendString:[NSString stringWithFormat:@"%@,",personStr]];
    }
    return strM.copy;
}




@end
